package com.chenfan.common.extension.util;

import lombok.extern.slf4j.Slf4j;

import java.util.Map;
import java.util.UUID;
import java.util.concurrent.ConcurrentHashMap;

/**
 * 虚拟机关闭钩子
 *
 * @author wulg
 * @date 2021-12-06
 **/
@Slf4j
public final class ApplicationShutdownHook {

    private static Map<String, Runnable> MAP = new ConcurrentHashMap<>(8);

    static {
        Runtime.getRuntime().addShutdownHook(new Thread(() -> {
            if(MAP.size() == 0) {
                return;
            }
            log.info("application shutdown hook start!");
            for(Map.Entry<String, Runnable> entry : MAP.entrySet()) {
                try {
                    entry.getValue().run();
                } catch (Exception e) {
                    log.error(e.getMessage(), e);
                }
            }
            MAP.clear();
            log.info("application shutdown hook end!");
        }));
    }

    /**
     * 添加钩子
     * @param runnable
     */
    public static void add(Runnable runnable) {
        MAP.putIfAbsent(UUID.randomUUID().toString(), runnable);
    }
}
